<template>
  <div class="supplier-form">
    <div class="page-header">
      <div class="header-left">
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
        <h2>{{ isEdit ? '编辑供应商' : '新增供应商' }}</h2>
      </div>
      <div class="header-right">
        <el-button @click="goBack">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </div>
    </div>

    <div class="form-content">
      <el-form
        ref="supplierForm"
        :model="formData"
        :rules="rules"
        label-width="120px"
        class="supplier-form-container"
      >
        <!-- 基本信息 -->
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="供应商名称" prop="name">
                <el-input
                  v-model="formData.name"
                  placeholder="请输入供应商名称"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供应商编码" prop="code">
                <el-input
                  v-model="formData.code"
                  placeholder="请输入供应商编码"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="企业类型" prop="type">
                <el-select
                  v-model="formData.type"
                  placeholder="请选择企业类型"
                  style="width: 100%"
                  clearable
                >
                  <el-option label="生产企业" value="生产企业" />
                  <el-option label="贸易企业" value="贸易企业" />
                  <el-option label="代理商" value="代理商" />
                  <el-option label="其他" value="其他" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合作状态" prop="status">
                <el-radio-group v-model="formData.status">
                  <el-radio :label="1">合作中</el-radio>
                  <el-radio :label="0">已终止</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系人" prop="contactPerson">
                <el-input
                  v-model="formData.contactPerson"
                  placeholder="请输入联系人姓名"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="phone">
                <el-input
                  v-model="formData.phone"
                  placeholder="请输入联系电话"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="邮箱地址" prop="email">
                <el-input
                  v-model="formData.email"
                  placeholder="请输入邮箱地址"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="传真号码" prop="fax">
                <el-input
                  v-model="formData.fax"
                  placeholder="请输入传真号码"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="公司地址" prop="address">
                <el-input
                  v-model="formData.address"
                  placeholder="请输入公司详细地址"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="公司简介" prop="description">
                <el-input
                  v-model="formData.description"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入公司简介"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 合作信息 -->
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <span>合作信息</span>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合作时间" prop="cooperationDate">
                <el-date-picker
                  v-model="formData.cooperationDate"
                  type="date"
                  placeholder="选择合作开始时间"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合作等级" prop="rating">
                <el-rate
                  v-model="formData.rating"
                  :max="5"
                  show-score
                  score-template="{value}分"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="信用额度" prop="creditLimit">
                <el-input-number
                  v-model="formData.creditLimit"
                  :precision="2"
                  :step="1000"
                  :min="0"
                  style="width: 100%"
                  placeholder="信用额度(万元)"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="账期(天)" prop="paymentTerm">
                <el-input-number
                  v-model="formData.paymentTerm"
                  :min="0"
                  :max="365"
                  style="width: 100%"
                  placeholder="账期天数"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="结算方式" prop="paymentMethod">
                <el-select
                  v-model="formData.paymentMethod"
                  placeholder="请选择结算方式"
                  style="width: 100%"
                  clearable
                >
                  <el-option label="月结" value="月结" />
                  <el-option label="现款现货" value="现款现货" />
                  <el-option label="预付款" value="预付款" />
                  <el-option label="其他" value="其他" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="运输方式" prop="transportMethod">
                <el-select
                  v-model="formData.transportMethod"
                  placeholder="请选择运输方式"
                  style="width: 100%"
                  clearable
                >
                  <el-option label="自提" value="自提" />
                  <el-option label="送货上门" value="送货上门" />
                  <el-option label="第三方物流" value="第三方物流" />
                  <el-option label="其他" value="其他" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 资质信息 -->
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <span>资质信息</span>
              <el-button type="primary" size="small" @click="addQualification">
                <el-icon><Plus /></el-icon>
                添加资质
              </el-button>
            </div>
          </template>
          
          <div v-for="(qualification, index) in formData.qualifications" :key="index" class="qualification-item">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item :label="index === 0 ? '资质名称' : ''" :prop="`qualifications.${index}.name`">
                  <el-input
                    v-model="qualification.name"
                    placeholder="资质名称"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item :label="index === 0 ? '证书编号' : ''" :prop="`qualifications.${index}.number`">
                  <el-input
                    v-model="qualification.number"
                    placeholder="证书编号"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item :label="index === 0 ? '发证日期' : ''" :prop="`qualifications.${index}.issueDate`">
                  <el-date-picker
                    v-model="qualification.issueDate"
                    type="date"
                    placeholder="发证日期"
                    style="width: 100%"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item :label="index === 0 ? '有效期至' : ''" :prop="`qualifications.${index}.expiryDate`">
                  <el-date-picker
                    v-model="qualification.expiryDate"
                    type="date"
                    placeholder="有效期至"
                    style="width: 100%"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-form-item :label="index === 0 ? '操作' : ''">
                  <el-button type="danger" size="small" @click="removeQualification(index)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-card>

        <!-- 其他信息 -->
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <span>其他信息</span>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="排序" prop="sort">
                <el-input-number
                  v-model="formData.sort"
                  :min="0"
                  :max="999"
                  style="width: 100%"
                  placeholder="排序值"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注" prop="remarks">
                <el-input
                  v-model="formData.remarks"
                  placeholder="请输入备注信息"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Plus, Delete } from '@element-plus/icons-vue'

export default defineComponent({
  name: 'SupplierForm',
  components: {
    ArrowLeft,
    Plus,
    Delete
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const supplierForm = ref(null)
    const submitLoading = ref(false)
    
    // 判断是否为编辑模式
    const isEdit = computed(() => {
      return !!route.params.id
    })
    
    // 表单数据
    const formData = reactive({
      id: null,
      name: '',
      code: '',
      type: '',
      status: 1,
      contactPerson: '',
      phone: '',
      email: '',
      fax: '',
      address: '',
      description: '',
      cooperationDate: '',
      rating: 3,
      creditLimit: null,
      paymentTerm: 30,
      paymentMethod: '',
      transportMethod: '',
      qualifications: [],
      sort: 0,
      remarks: ''
    })
    
    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入供应商名称', trigger: 'blur' },
        { min: 2, max: 100, message: '供应商名称长度在 2 到 100 个字符', trigger: 'blur' }
      ],
      code: [
        { required: true, message: '请输入供应商编码', trigger: 'blur' },
        { pattern: /^[A-Z0-9_-]+$/, message: '供应商编码只能包含大写字母、数字、下划线和横线', trigger: 'blur' }
      ],
      type: [
        { required: true, message: '请选择企业类型', trigger: 'change' }
      ],
      contactPerson: [
        { required: true, message: '请输入联系人', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      address: [
        { required: true, message: '请输入公司地址', trigger: 'blur' }
      ],
      cooperationDate: [
        { required: true, message: '请选择合作时间', trigger: 'change' }
      ]
    }
    
    // 加载供应商详情（编辑模式）
    const loadSupplierDetail = async () => {
      if (!isEdit.value) return
      
      try {
        // 模拟API请求
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        // 模拟编辑数据
        Object.assign(formData, {
          id: route.params.id,
          name: '绿色农场供应商',
          code: 'SUP001',
          type: '生产企业',
          status: 1,
          contactPerson: '张经理',
          phone: '13800138000',
          email: 'zhang@greenfarm.com',
          fax: '010-12345678',
          address: '北京市朝阳区绿色农业园区A区1号',
          description: '专业从事有机农产品种植和销售，拥有完善的种植基地和配送体系。',
          cooperationDate: '2023-01-15',
          rating: 4.5,
          creditLimit: 500,
          paymentTerm: 30,
          paymentMethod: '月结',
          transportMethod: '送货上门',
          qualifications: [
            {
              name: '食品生产许可证',
              number: 'SC101234567890',
              issueDate: '2023-01-01',
              expiryDate: '2028-01-01'
            },
            {
              name: '有机产品认证证书',
              number: 'ORG2023001',
              issueDate: '2023-03-15',
              expiryDate: '2026-03-15'
            }
          ],
          sort: 1,
          remarks: '优质供应商，合作愉快'
        })
      } catch (error) {
        console.error('加载供应商详情失败:', error)
        ElMessage.error('加载供应商详情失败')
      }
    }
    
    // 添加资质
    const addQualification = () => {
      formData.qualifications.push({
        name: '',
        number: '',
        issueDate: '',
        expiryDate: ''
      })
    }
    
    // 删除资质
    const removeQualification = (index) => {
      formData.qualifications.splice(index, 1)
    }
    
    // 提交表单
    const handleSubmit = async () => {
      try {
        await supplierForm.value.validate()
        submitLoading.value = true
        
        // 模拟提交请求
        await new Promise(resolve => setTimeout(resolve, 2000))
        
        ElMessage.success(isEdit.value ? '供应商更新成功' : '供应商添加成功')
        router.push('/suppliers/list')
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败，请检查输入信息')
      } finally {
        submitLoading.value = false
      }
    }
    
    // 返回上一页
    const goBack = () => {
      router.go(-1)
    }
    
    onMounted(() => {
      loadSupplierDetail()
    })
    
    return {
      isEdit,
      supplierForm,
      formData,
      rules,
      submitLoading,
      loadSupplierDetail,
      addQualification,
      removeQualification,
      handleSubmit,
      goBack
    }
  }
})
</script>

<style scoped>
.supplier-form {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-left h2 {
  margin: 0;
  color: #2563eb;
}

.form-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.form-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.qualification-item {
  border: 1px solid #e1e5e9;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  background: #f8f9fa;
}

.supplier-form-container {
  max-width: 1200px;
  margin: 0 auto;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .header-right {
    width: 100%;
    display: flex;
    gap: 10px;
  }
  
  .form-content {
    padding: 10px;
  }
}
</style> 